﻿"use strict";

// 模拟存储的token
var token = (Math.random() * 10000) + "";

// 创建链接
var builder = new signalR.HubConnectionBuilder();
console.info(builder)
var connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .build();

// 禁用按钮，直到链接初始化完成
document.getElementById("sendButton").disabled = true;

// 监听ReceiveMessage返回
connection.on("ReceiveMessage", function (user, message) {
    var li = document.createElement("li");
    document.getElementById("messagesList").appendChild(li);
    li.textContent = `${user} says ${message}`;
});

// 监听LoginComplete
connection.on("LoginComplete", function (jsonMsg) {
    var li = document.createElement("li");
    document.getElementById("messagesList").appendChild(li);
    li.textContent = `${jsonMsg}`;
});

// 启动链接
connection.start().then(function () {
    // 成功则启动发送信息按钮
    document.getElementById("sendButton").disabled = false;
    // 调用登录方法，传入token进行验证
    connection.invoke("Login", token).catch(function (err) {
        return console.error(err.toString());
    });

}).catch(function (err) {
    // 失败则返回错误信息
    return console.error(err.toString());
});

// 发送信息按钮增加点击事件
document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    // 调用发送信息方法，传入user和message
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});